﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.EnterpriseService;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.ModelService;
using Newtonsoft.Json;
using Fly.Common.Linq;
using Fly.Common.WorkFlow;

namespace RN.ERP.Web.Enterprise
{
    public partial class EnterpriseQualityInfo : BasePage
    {
        private EnterpriseServiceClient enterpriseServiceClient = new EnterpriseServiceClient();
        private BasicServiceClient basicServiceClient = new BasicServiceClient();
        /// <summary>
        /// 资质guid
        /// </summary>
        private string QualityGuid
        {
            get
            {
                return Request.QueryString["QualityGuid"];
            }
        }
        private string CorpUserGuid
        {
            get
            {
                return Request.QueryString["CorpUserGuid"];
            }
        }
        /// <summary>
        /// 操作类型
        /// Add：添加,Edit:修改
        /// </summary>
        private string OperateType
        {
            get
            {
                return Request.QueryString["OperateType"];
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //BindDropDown();
                BindData();
                InitPage();
            }
        }

        private void BindData()
        {
            Guid guid = Guid.Empty;
            if (UserInfo == null)
            {
                return;
            }
            string corpUserGuid = GetCorpUserGuid();
            hdnCorpUserGuid.Value = corpUserGuid;
            hdnOperateType.Value = OperateType;
            hdnQualityGuid.Value = Guid.Empty.ToString();
            List<QueryCompanyInfoCondition> list = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition condition = new QueryCompanyInfoCondition();
            condition.CorpUserGuid = new ParameterValue<Guid>() { O=OptEnum.Equal,V=Guid.Parse( corpUserGuid)};
            list.Add(condition);
            var corp =JsonConvert.DeserializeObject<CompanyInfo>( enterpriseServiceClient.GetCompanyBisicInfo(JsonConvert.SerializeObject(list),UserInfo.CurrentArea));

            corpqual.SetRole = corp.RoleId.ToString();
            if (OperateType == "Edit")
            {
                ////资质存在，修改
                Guid.TryParse(QualityGuid, out guid);
                QueryCorpQualityInfoCondition queryQuality = new QueryCorpQualityInfoCondition();
                queryQuality.QualityGuid = new ParameterValue<Guid>() { V = guid, O = OptEnum.Equal };
                List<QueryCorpQualityInfoCondition> queryList = new List<QueryCorpQualityInfoCondition>();
                queryList.Add(queryQuality);
                var qualitys = JsonConvert.DeserializeObject<List<tb_Corp_Quality>>(enterpriseServiceClient.GetCompanyQualities(corpUserGuid, JsonConvert.SerializeObject(queryList), UserInfo.CurrentArea));
                if (qualitys == null || qualitys.Count <= 0)
                {
                    return;
                }
                var qual = qualitys[0];
                chkIsMain.Checked = qual.IsMain ?? false;
                corpqual.SetQualGuid = qual.QualityGuid.ToString();
                
                txtQualityCode.Text = qual.QualityCode;
                txtGetDate.Value = qual.GetDate.HasValue?((DateTime)qual.GetDate).ToShortDateString():"";
                txtzzzEndDate.Value = qual.zzzEndDate.HasValue ? ((DateTime)qual.zzzEndDate).ToShortDateString() : "";
                hdnIsMain.Value = (qual.IsMain ?? false).ToString();
                hdnQualityGuid.Value = qual.QualityGuid.ToString();

                Imgzz.ImageUrl = "../Handlers/GetFileHandler.ashx?fileName=" + QualityGuid + ".jpg" + "&sysCode=EF&funcCode=CorpZZ";
            }
            else if (OperateType == "Add")
            {
                ////添加资质则QualityGuid进行生成
                hdnQualityGuid.Value = Guid.NewGuid().ToString();
            }
        }

        private void InitPage()
        {
            string UserGuid = GetCorpUserGuid();
            Guid guid = Guid.Empty;
            Guid.TryParse(UserGuid, out guid);
            Guid corpUserGuid = guid;
            if (corpUserGuid != Guid.Empty)
            {
                var flowCode = GetEmbranchmentFlow(corpUserGuid);
                var corpInfo = GetCompanyinfo(corpUserGuid.ToString());
                var Embranchments = enterpriseServiceClient.GetCorpEmbranchments(JsonConvert.SerializeObject(corpInfo));
                var CorpEmbranchments = JsonConvert.DeserializeObject<IList<Tb_Corp_Embranchment>>(Embranchments);
                OperationResult flowEditResult = new OperationResult();
                flowEditResult.Result = true;
                foreach (var em in CorpEmbranchments)
                {
                    ////在任何市场范围上报后基本则不可编辑
                    var emFlow = GetEmbranchmentFlow(em.AreaCode);
                    var emFlowEditResult = JsonConvert.DeserializeObject<FlowResult>(basicServiceClient.GetNextFlowCode(UserInfo.RoleId, "", em.AreaCode, corpInfo.classID.ToString(), emFlow, BasicService.OptType.Edit));
                    if (!emFlowEditResult.Result)
                    {
                        flowEditResult.Result = false;
                        break;
                    }
                }
                if (!flowEditResult.Result)
                {
                    SetControlDisable();
                }
                else
                {
                    hdnEditModel.Value = "0";
                }
            }
            ////企业端可以查看其他企业信息，但不允许做任何操作
            if (!string.IsNullOrEmpty(CorpUserGuid)&&CorpUserGuid != UserInfo.CorpUserGuid)
            {
                SetControlDisable();
            }
        }

        public string GetEmbranchmentFlow(object areaCode)
        {
            string flowTitle = "";
            if (areaCode == null)
            {
                return flowTitle;
            }
            string code = areaCode.ToString();
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = Guid.Parse(GetCorpUserGuid());
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }

        private string GetEmbranchmentFlow(Guid corpUserGuid)
        {
            string flowTitle = "";
            if (string.IsNullOrEmpty(UserInfo.CurrentArea))
            {
                return flowTitle;
            }
            string code = UserInfo.CurrentArea;
            Tb_Corp_CompanyInfo corpInfo = new Tb_Corp_CompanyInfo();
            corpInfo.CorpUserGuid = corpUserGuid;
            var flow = JsonConvert.DeserializeObject<Tb_FlowCode>(enterpriseServiceClient.GetCorpFlowCode(JsonConvert.SerializeObject(corpInfo), code));
            if (flow != null)
            {
                flowTitle = string.IsNullOrEmpty(flow.FlowCode) ? "" : flow.FlowCode;
            }
            return flowTitle;
        }
        private Tb_Corp_CompanyInfo GetCompanyinfo(string corpUserGuid)
        {
            QueryCompanyInfoCondition queryCompanyInfoCondition =
               new QueryCompanyInfoCondition() { CorpUserGuid = new ParameterValue<Guid>() { V = Guid.Parse(corpUserGuid), O = OptEnum.Equal } };
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            var corpInfo = JsonConvert.DeserializeObject<Tb_Corp_CompanyInfo>(enterpriseServiceClient.GetCompanyInfo(JsonConvert.SerializeObject(queryCompanyInfoList), UserInfo.CurrentArea));
            return corpInfo;
        }

        private string GetCorpUserGuid()
        {
            if (string.IsNullOrEmpty(CorpUserGuid))
            {
                return UserInfo.CorpUserGuid;
            }
            return CorpUserGuid;
        }

        private void SetControlDisable()
        {
            ////不可编辑
            hdnEditModel.Value = "1";
            chkIsMain.Enabled = true;
            txtQualityCode.Enabled = true;
            txtGetDate.Disabled = false;
            txtzzzEndDate.Disabled = false;
            btnUpload.Enabled = true;
            btnSubmit.Visible = true;
            btnCancel.Visible = true;
            corpqual.Enable = true;
        }
    }
}